package cn.bocweb.spinning.view.forun;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.BindColor;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.CommentBean;
import cn.bocweb.spinning.model.Bean.CommentReplyBean;
import cn.bocweb.spinning.model.Bean.ForumCollectBean;
import cn.bocweb.spinning.model.Bean.ForumDetailBean;
import cn.bocweb.spinning.model.Bean.ForumReplyBean;
import cn.bocweb.spinning.model.Bean.ForumUpBean;
import cn.bocweb.spinning.model.Bean.MatchInviteBean;
import cn.bocweb.spinning.model.Bean.ReportBean;
import cn.bocweb.spinning.model.Bean.ReportTypeBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.util.WXUtil;
import cn.bocweb.spinning.view.activity.ImgDetailActivity;
import cn.bocweb.spinning.view.activity.LoginAcivity;

import cn.bocweb.spinning.view.adapter.GvImgAdapter;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.ContainsEmojiEditText;
import cn.bocweb.spinning.view.common.SwipeRefreshHelper;
import cn.bocweb.spinning.view.dialog.LoadingDialog;
import cn.bocweb.spinning.view.dialog.ReportTypeDialog;
import cn.bocweb.spinning.view.dialog.ShareDialog;
import de.greenrobot.event.EventBus;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

public class ForunDetailActivity extends BaseActivity {

    private static final int COMMENT = 1;
    private static final int COMMENT_REPLY = 2;
    List<ForumDetailBean.CommentBean> list;
    ForunDetailAdapter forunDetailAdapter;
    UserPresenter mPresenter;
    String userid, id, icon;
    SwipeRefreshHelper mSwipeRefreshHelper;
    LoadingDialog mLoadingDialog;
    boolean liked, collected, isMine, isCommentMySelf, isReceiverMe, isReply;
    ReportTypeDialog mReportTypeDialog;
    GvImgAdapter rvImgAdapter;
    String reportType, nickname;
    int comment_state = COMMENT; // 1 为 评论, 2 为 贴住回复评论
    int photo_size = 3;
    ForumReplyBean.DataBean.ReplyBean mReplyBean;
    ShareDialog mShareDialog;
    UserBean.DataEntity dataEntity;
    String connect_id;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.forun_detail_list)
    ListView forunDetailList;
    @Bind(R.id.tips)
    RelativeLayout mTips;
    @Bind(R.id.title)
    TextView mTitle;
    @Bind(R.id.time)
    TextView mTime;
    @Bind(R.id.report)
    TextView mReport;

    @Bind(R.id.add_image)
    RelativeLayout mAddImage;
    @Bind(R.id.people_count)
    TextView mPeopleCount;
    @Bind(R.id.img_count)
    TextView imgCount;
    @Bind(R.id.zan)
    ImageView mZan;
    @Bind(R.id.write_quiz_pic)
    LinearLayout write_quiz_pic;
    @Bind(R.id.btn_photo)
    ImageView mphoto;
    @Bind(R.id.rv_img)
    RecyclerView rv_img;
    @Bind(R.id.edit)
    ContainsEmojiEditText mEdit;
    @Bind(R.id.send)
    Button mSend;
    @Bind(R.id.forun_detail_collect)
    ImageView mForunDetailCollect;
    @Bind(R.id.forun_detail_share)
    ImageView mForunDetailShare;
    @Bind(R.id.content)
    TextView mContent;
    @Bind(R.id.refresh)
    SwipeRefreshLayout mRefresh;
    @Bind(R.id.img_layout)
    LinearLayout mImgLayout;
    @Bind(R.id.edit_parent)
    LinearLayout mEditParent;
    @BindColor(R.color.white)
    int white;
    @Bind(R.id.hots)
    RelativeLayout mHots;
    int page = 1;
    @Bind(R.id.like_count)
    TextView mLikeCount;
    int photoCount = 0;
    int friend_1_timeline_2 = 0;
    String location;
    LocationClient client;
    List<File> mFiles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forun_detail);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        mLoadingDialog = new LoadingDialog(this);
        mShareDialog = new ShareDialog(this);
        mLoadingDialog.show();
        list = new ArrayList<>();
        forunDetailAdapter = new ForunDetailAdapter(this, list);
        mPresenter = new UserPresenterImp();
        mReportTypeDialog = new ReportTypeDialog(this);
        dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);
        userid = dataEntity.getUserid();
        nickname = dataEntity.getNickname();
        icon = dataEntity.getUthumb();

        mEditParent.setFocusable(true);

        mFiles = new ArrayList<>();
        rvImgAdapter = new GvImgAdapter(mFiles);

        initReportType();
        initListView();
        initIntent();
        initToolbar();
        initShare();
        initRvImg();
        initLoacation();
    }

    private void initLoacation() {
        client = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setIsNeedAddress(true);
        option.setIsNeedLocationDescribe(true);
        client.setLocOption(option);
        client.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                location = bdLocation.getCity();
            }
        });
        client.start();
    }

    private void initShare() {
        mShareDialog.setOnShareListener(new ShareDialog.OnShareListener() {
            @Override
            public void shareTimeLine() {
                mPresenter.matchInvite();
                friend_1_timeline_2 = 2;
                mShareDialog.dismiss();
            }

            @Override
            public void shareFriend() {
                mPresenter.matchInvite();
                friend_1_timeline_2 = 1;
                mShareDialog.dismiss();
            }
        });
    }

    public void onEventMainThread(MatchInviteBean bean) {
        if (bean.getReturn_code() == 0) {
            if (friend_1_timeline_2 == 1) {
                WXUtil.WXShareToFriend(bean.getUrl(), this);
            } else {
                WXUtil.WXShareToTimeline(bean.getUrl(), this);
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        if (mReportTypeDialog.isShowing()) {
            mReportTypeDialog.dismiss();
        }
    }

    @Override
    protected void onStop() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (client != null && client.isStarted()) {
            client.stop();
        }
        super.onStop();
    }

    public void onEventMainThread(ForumDetailBean bean) {
        if (mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        if (mRefresh.isRefreshing()) {
            mRefresh.setRefreshing(false);
        }
        if (bean.getReturn_code() == 0) {
            if (bean.getData() != null) {
                initData(bean.getData());

//                initToolbarName(bean.getData().getUserid(), bean.getData().getNickname());
            }
            if (bean.getComment() != null) {
                initList(bean.getComment());
            }

            isMine = bean.getData().getUserid().equals(userid);
            masterReply();
        } else if (bean.getReturn_code() == -203) {
            DeviceUtil.MyToast(this, "已经是最后一页");
            page--;
        } else {
            DeviceUtil.Log(bean.getMsg());
        }
    }


    public void onEventMainThread(ForumUpBean bean) {

        if (bean.getReturn_code() == 0) {
            liked = !liked;
            int likeIcon = liked ? R.mipmap.liked : R.mipmap.dianzan;
            int upnum = Integer.parseInt(mLikeCount.getText().toString());
            upnum = liked ? upnum + 1 : upnum - 1;
            mZan.setImageResource(likeIcon);
            mLikeCount.setText(String.valueOf(upnum));
            DeviceUtil.MyToast(this, bean.getMsg());
        } else if (bean.getReturn_code() == -201) {
            DeviceUtil.MyToast(this, "请先登录");
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    public void onEventMainThread(ForumCollectBean bean) {

        if (bean.getReturn_code() == 0) {
            collected = !collected;
            int collectIcon = collected ? R.mipmap.collected : R.mipmap.drawer_collect;
            mForunDetailCollect.setImageResource(collectIcon);
            DeviceUtil.MyToast(this, bean.getMsg());
        } else if (bean.getReturn_code() == -201) {
            DeviceUtil.MyToast(this, "请先登录");
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    public void onEventMainThread(ReportTypeBean bean) {
        if (bean.getReturn_code() == 0) {
            mReportTypeDialog.setStringList(bean.getData());
        }
    }

    public void onEventMainThread(CommentBean bean) {
        DeviceUtil.MyToast(this, bean.getMsg());
        if (bean.getReturn_code() == 0) {
            ForumDetailBean.CommentBean mCommentBean = new ForumDetailBean.CommentBean();
            mCommentBean.setContent(mEdit.getText().toString());
            mCommentBean.setNickname(nickname);
            mCommentBean.setTimeline(String.valueOf(System.currentTimeMillis() / 1000));
            mCommentBean.setUthumb(icon);
            mCommentBean.setLocation(location);
            list.add(0, mCommentBean);
            forunDetailAdapter.notifyDataSetChanged();
            mEdit.setText("");
            mFiles.clear();
            rvImgAdapter.notifyDataSetChanged();
            imgCount.setVisibility(View.GONE);
            rv_img.setVisibility(View.GONE);
            mPeopleCount.setText(String.valueOf(Integer.parseInt(mPeopleCount.getText().toString()) + 1));
        }
    }

    public void onEventMainThread(ForumReplyBean bean) {
        if (bean.getReturn_code() == 0) {

        }
    }

    public void onEventMainThread(ReportBean bean) {
        if (bean.getReturn_code() == -201) {
            DeviceUtil.MyToast(this, "请先登录");
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
        mReportTypeDialog.dismiss();
    }

    public void onEventMainThread(CommentReplyBean bean) {
        if (bean.getReturn_code() == 0) {
            ForumDetailBean.CommentBean mCommentBean = new ForumDetailBean.CommentBean();
            mCommentBean.setContent(mEdit.getText().toString());
            mCommentBean.setNickname(nickname);
            mCommentBean.setTimeline(String.valueOf(System.currentTimeMillis() / 1000));
            mCommentBean.setUthumb(icon);
            mCommentBean.setLocation(location);
            mCommentBean.setReceiver(bean.getReceiver());
            mCommentBean.setSender(dataEntity.getUserid());
            list.add(0, mCommentBean);
            forunDetailAdapter.notifyDataSetChanged();
            mEdit.setText("");
            mPeopleCount.setText(String.valueOf(Integer.parseInt(mPeopleCount.getText().toString()) + 1));
            mEdit.setText("");
            comment_state = COMMENT;

            mFiles.clear();
            rvImgAdapter.notifyDataSetChanged();
            imgCount.setVisibility(View.GONE);
            rv_img.setVisibility(View.GONE);
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            // 隐藏软键盘
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
            DeviceUtil.MyToast(this, bean.getMsg());
        } else if (bean.getReturn_code() == -201) {
            DeviceUtil.MyToast(this, "请先登录");
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    private void initToolbarName(String id, String nickname) {
        String title = id.equals(dataEntity.getUserid())
                ? "我的帖子"
                : new StringBuffer(nickname).append("的帖子").toString();
        toolbar.setTitle(title);
    }

    private void masterReply() {

        forunDetailList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                comment_state = COMMENT_REPLY;
                if (isMine) {
                    isCommentMySelf = list.get(position).getSender().equals(dataEntity.getUserid());
                } else {
                    isReceiverMe = list.get(position).getReceiverId().equals(dataEntity.getUserid());
                }
                if (isReceiverMe || isCommentMySelf) {
                    mEdit.setHint("回复" + list.get(position).getNickname());
                }
                connect_id = list.get(position).getId();
            }
        });
    }

    private void initReportType() {
        mReportTypeDialog.setOnSelectListener(new ReportTypeDialog.OnSelectListener() {
            @Override
            public void onClick(String title) {
                reportType = title;
                mPresenter.report(dataEntity.getUserid(), id, title);
            }
        });
    }

    private void initList(List<ForumDetailBean.CommentBean> been) {
        list.addAll(been);
        forunDetailAdapter.notifyDataSetChanged();
    }

    private void initData(final ForumDetailBean.DataBean bean) {
        mTitle.setText(bean.getTitle());
        mTime.setText(DeviceUtil.getTimeByTwoTimeStampForPhp(
                Long.parseLong(bean.getTimeline()) * 1000,
                System.currentTimeMillis()));
        mPeopleCount.setText(bean.getNum());
        mContent.setText(bean.getContent());
        liked = bean.getIsup().equals("1");
        collected = bean.getIscollect().equals("1");
        int collectIcon = bean.getIscollect().equals("1") ? R.mipmap.collected : R.mipmap.drawer_collect;
        mForunDetailCollect.setImageResource(collectIcon);
        int likeIcon = bean.getIsup().equals("1") ? R.mipmap.liked : R.mipmap.dianzan;
        mZan.setImageResource(likeIcon);
        int tips = bean.getFlag().equals("1") ? View.VISIBLE : View.GONE;
        mTips.setVisibility(tips);
        int hots = bean.getHot().endsWith("1") ? View.VISIBLE : View.GONE;
        mHots.setVisibility(hots);
        int childNum = 0;
        if (bean.getPhoto().isEmpty()) {
            mImgLayout.setVisibility(View.GONE);
        } else {
            for (int i = 0; i < bean.getPhoto().size(); i++) {
                Glide
                        .with(this)
                        .load(bean.getPhoto().get(i))
                        .placeholder(R.mipmap.banner_empty)
                        .into((ImageView) mImgLayout.getChildAt(childNum));

                final int finalI = i;
                mImgLayout.getChildAt(childNum).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ForunDetailActivity.this, ImgDetailActivity.class);
                        intent.putStringArrayListExtra(Constant.IMG_DETAIL_URL, (ArrayList<String>) bean.getPhoto());
                        startActivity(intent);
                    }
                });
                childNum += 2;
            }
        }
        mLikeCount.setText(bean.getUpnum());
    }

    private void initIntent() {
        Intent intent = getIntent();
        if (intent.getSerializableExtra(Constant.REPLY_TO_FORUN_DETAIL_BEAN) != null) {
            mReplyBean = (ForumReplyBean.DataBean.ReplyBean) intent.getSerializableExtra(Constant.REPLY_TO_FORUN_DETAIL_BEAN);
            id = intent.getStringExtra(Constant.REPLY_TO_FORUN_DETAIL_FORUM);
            isReply = true;
            initReply();
        } else {
            id = intent.getStringExtra(Constant.TO_FORUM_DETAIL);

        }
        mPresenter.forumDetail(dataEntity.getUserid(), id, page);
        mPresenter.reportType();
    }

    private void initReply() {
        mEdit.setHint(new StringBuffer("回复").append(mReplyBean.getNickname()));
        connect_id = mReplyBean.getId();
    }

    private void initToolbar() {
        toolbar.setNavigationIcon(R.mipmap.btn_exit);
        toolbar.setTitleTextColor(white);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initListView() {
        mSwipeRefreshHelper = new SwipeRefreshHelper(mRefresh, forunDetailList, new SwipeRefreshHelper.OnSwipeRefreshListener() {
            @Override
            public void onRefresh() {
                list.clear();
                page = 1;
                forunDetailAdapter.notifyDataSetChanged();
                mPresenter.forumDetail(dataEntity.getUserid(), id, page);
            }

            @Override
            public void onLoad() {
                page++;
                mPresenter.forumDetail(dataEntity.getUserid(), id, page);
            }
        });
        forunDetailList.setAdapter(forunDetailAdapter);
    }

    @OnClick({R.id.forun_detail_collect, R.id.forun_detail_share, R.id.report, R.id.zan, R.id.send, R.id.btn_photo})
    public void onClick(View view) {
        dataEntity.readInfoFromLocal(this);
        switch (view.getId()) {
            case R.id.forun_detail_collect:
                if (TextUtils.isEmpty(dataEntity.getUserid())) {
                    Intent intent = new Intent(this, LoginAcivity.class);
                    startActivity(intent);
                    break;
                }
                mPresenter.forumCollect(dataEntity.getUserid(), id, collected);
                break;
            case R.id.forun_detail_share:
                mShareDialog.show();
                break;
            case R.id.report:
                mReportTypeDialog.show();
                break;

            case R.id.zan:
                if (TextUtils.isEmpty(dataEntity.getUserid())) {
                    Intent intent = new Intent(this, LoginAcivity.class);
                    startActivity(intent);
                    break;
                }
                mPresenter.forumUp(dataEntity.getUserid(), id, liked);
                break;
            case R.id.btn_photo:
                write_quiz_pic.setVisibility(View.VISIBLE);
                PhotoPickerIntent intent1 = new PhotoPickerIntent(ForunDetailActivity.this);
                intent1.setPhotoCount(photo_size);
                intent1.setShowCamera(true);
                intent1.setShowGif(false);
                startActivityForResult(intent1, Constant.SELECT_PHOTO_FOR_QA);
                break;
            case R.id.send:
                if (TextUtils.isEmpty(dataEntity.getUserid())) {
                    Intent intent = new Intent(this, LoginAcivity.class);
                    startActivity(intent);
                    break;
                }
                if (!isReply) {
                        if (comment_state == COMMENT && !isMine) {
                            // TODO: 16/6/16 定位还没做
                            mPresenter.forumComment(dataEntity.getUserid(), id, mEdit.getText().toString(), location, mFiles);
                        } else if (comment_state == COMMENT_REPLY && isMine) {
                            if (!isCommentMySelf) {
                                mPresenter.commentReply(connect_id, dataEntity.getUserid(), mEdit.getText().toString(), mFiles);
                            } else {
                                DeviceUtil.MyToast(ForunDetailActivity.this, "自己不能评论自己的回复");
                            }
                        } else if (comment_state == COMMENT && isMine) {
                            DeviceUtil.MyToast(ForunDetailActivity.this, "帖主不能回复自己的帖子");
                        } else if (comment_state == COMMENT_REPLY && !isMine) {
                            if (isReceiverMe) {
                                mPresenter.commentReply(connect_id, dataEntity.getUserid(), mEdit.getText().toString(), mFiles);
                                if (mFiles != null) {
                                    mPresenter.commentReply(connect_id, dataEntity.getUserid(), mEdit.getText().toString(), mFiles);
                                }
                            }
                        }
                    } else {
                    mPresenter.commentReply(connect_id, dataEntity.getUserid(), mEdit.getText().toString(), mFiles);
                    }
                break;
        }
    }

    private void initRvImg() {
        mZan.requestFocus();
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        rv_img.setAdapter(rvImgAdapter);
        rv_img.setLayoutManager(manager);

        rvImgAdapter.setOnItemClickListener(new GvImgAdapter.OnItemClickListener() {
            @Override
            public void onClick() {
                if (Build.VERSION.SDK_INT >= 23) {
                    int camarePermission = ContextCompat.checkSelfPermission(ForunDetailActivity.this, Manifest.permission.CAMERA);
                    int photoPermission = ContextCompat.checkSelfPermission(ForunDetailActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
                    if (camarePermission != PackageManager.PERMISSION_GRANTED || photoPermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(
                                ForunDetailActivity.this,
                                new String[]{
                                        Manifest.permission.CAMERA,
                                        Manifest.permission.READ_EXTERNAL_STORAGE}, 301);
                        return;
                    }
                }
                PhotoPickerIntent intent = new PhotoPickerIntent(ForunDetailActivity.this);
                intent.setPhotoCount(photo_size);
                intent.setShowCamera(true);
                intent.setShowGif(false);
                startActivityForResult(intent, Constant.SELECT_PHOTO_FOR_QA);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constant.SELECT_PHOTO_FOR_QA) {
            if (data != null) {
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                if (photos.isEmpty()) {
                    imgCount.setVisibility(View.GONE);
                } else {

                    imgCount.setVisibility(View.VISIBLE);

                    rv_img.setVisibility(View.VISIBLE);
                    mAddImage.setVisibility(View.GONE);
                    for (String filePath : photos) {
                        File file = new File(filePath);
                        mFiles.add(file);
                    }
                    photo_size = 3 - mFiles.size();
                    imgCount.setText(String.valueOf(mFiles.size()));

                    photoCount = mFiles.size();
                    rvImgAdapter.notifyDataSetChanged();
                    rvImgAdapter.setOnImgDeleteListener(new GvImgAdapter.OnImgDeleteListener() {
                        @Override
                        public void onclick(int position) {
                            mFiles.remove(position);
                            photo_size++;
                            photoCount = mFiles.size();
                            imgCount.setText(String.valueOf(mFiles.size()));
                            rvImgAdapter.notifyDataSetChanged();
                            if (mFiles.size() == 0) {
                                imgCount.setVisibility(View.GONE);
                                mAddImage.setVisibility(View.GONE);
                            } else {
                                imgCount.setVisibility(View.VISIBLE);
                                mAddImage.setVisibility(View.GONE);
                            }
                        }
                    });
                }
            }
        }
    }
}
